/*
 * 文件名称:          EnumValueSerializer.java
 * 版权所有@ 2016——2017 无锡聆音科技有限公司，保留所有权利
 * 时间:             2016年7月27日 下午9:21:11
 */
package com.lingyin.json.serializer;

import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.serializer.FieldSerializer;
import com.alibaba.fastjson.serializer.FilterUtils;
import com.alibaba.fastjson.serializer.JSONSerializer;
import com.alibaba.fastjson.serializer.ObjectFieldSerializer;
import com.alibaba.fastjson.serializer.ObjectSerializer;
import com.alibaba.fastjson.serializer.SerialContext;
import com.alibaba.fastjson.serializer.SerializeWriter;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.util.FieldInfo;
import com.alibaba.fastjson.util.TypeUtils;

/**
 *    对枚举类型的对象，序列化其值内容，而不仅仅是名字。
 * 
 * @项目        jsonlib
 * 
 * @作者:       关宏新
 * 
 * @日期:       2016年7月27日
 * 
 * @负责人:    关宏新
 * 
 * @负责小组:   聆音项目组
 * 
 */
public class EnumValueSerializer implements ObjectSerializer
{

    private final FieldSerializer[] getters;
    private boolean ordinalEnable;   // 是否序列化序号
    private boolean nameEnable;      // 是否序列化名字
    private boolean writeAsArray = false;   // 内容序列化为数组形式

    /**
     * 构造枚举的序列化对象，序列化对象的所有属性值。
     * @param clazz 需要序列化的对象class
     */
    public EnumValueSerializer(Class<?> clazz)
    {
        this(clazz, (Map<String, String>)null);
    }
    
    /**
     * 构造枚举的序列化对象，序列化对象的所有属性值。
     * @param clazz 需要序列化的对象class
     * @param ordinalEnable 是否需要序列化ordinal值
     * @param nameEnable 是否需要序列化那么值
     */
    public EnumValueSerializer(Class<?> clazz, boolean ordinalEnable, boolean nameEnable)
    {
        this(clazz, (Map<String, String>)null, ordinalEnable, nameEnable);
    }

    /**
     * 构造枚举的序列化对象
     * @param clazz 需要序列化的对象class
     * @param properties 需要序列化的属性集合，不在该集合中的属性不序列化。
     */
    public EnumValueSerializer(Class<?> clazz, String...properties)
    {
        this(clazz, createAliasMap(properties));
    }
    
    /**
     * 构造枚举的序列化对象
     * @param clazz 需要序列化的对象class
     * @param properties 需要序列化的属性集合，不在该集合中的属性不序列化。
     * @param ordinalEnable 是否需要序列化ordinal值
     * @param nameEnable 是否需要序列化那么值
     */
    public EnumValueSerializer(Class<?> clazz, boolean ordinalEnable, boolean nameEnable, String...properties)
    {
        this(clazz, createAliasMap(properties), ordinalEnable, nameEnable);
    }

    /**
     * 构造枚举的序列化对象
     * @param clazz 需要序列化的对象class
     * @param properties 需要序列化的属性集合，不在该集合中的属性不序列化。
     */
    public EnumValueSerializer(Class<?> clazz, Map<String, String> properties)
    {
        this(clazz, properties, false, false);
    }
        
    /**
     * 构造枚举的序列化对象
     * @param clazz 需要序列化的对象class
     * @param properties 需要序列化的属性集合，不在该集合中的属性不序列化。
     * @param ordinalEnable 是否需要序列化ordinal值
     * @param nameEnable 是否需要序列化那么值
     */
    public EnumValueSerializer(Class<?> clazz, Map<String, String> properties, boolean ordinalEnable, boolean nameEnable)
    {
        List<FieldSerializer> getterList = new ArrayList<FieldSerializer>();
        List<FieldInfo> fieldInfoList = TypeUtils.computeGetters(clazz, properties, true);

        for (FieldInfo fieldInfo : fieldInfoList)
        {
            if ("declaringClass".equals(fieldInfo.getName()))   // 过滤该属性
            {
                continue;
            }
            getterList.add(createFieldSerializer(fieldInfo));
        }

        getters = getterList.toArray(new FieldSerializer[getterList.size()]);
        
        this.ordinalEnable = ordinalEnable;
        this.nameEnable = nameEnable;
    }

    /*
     * 转换为集合对象
     */
    private static Map<String, String> createAliasMap(String...properties)
    {
        Map<String, String> map = new HashMap<String, String>();
        for (String alias : properties)
        {
            map.put(alias, alias);
        }
        return map;
    }

    /**
     * 序列化枚举对象内容
     * @param serializer json序列化对象。
     * @param object 需要序列化的对象
     * @param fieldName 需要的属性名
     * @param fieldType 需要序列化的类型
     * @throws IOException 抛出io异常
     */
    public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType) throws IOException
    {
        SerializeWriter out = serializer.getWriter();
        if (object == null)
        {
            out.writeNull();
            return;
        }
        
        final FieldSerializer[] getters = this.getters;
        SerialContext parent = serializer.getContext();
        serializer.setContext(parent, object, fieldName, 0);
        //final boolean writeAsArray = serializer.isWriteAsArray(object, fieldType);

        try
        {
            final char startSeperator = writeAsArray ? '[' : '{';
            final char endSeperator = writeAsArray ? ']' : '}';
            out.append(startSeperator);

            if (getters.length > 0 && out.isEnabled(SerializerFeature.PrettyFormat))
            {
                serializer.incrementIndent();
                serializer.println();
            }

            boolean commaFlag = false;

            if (isWriteClassName(serializer, object, fieldType, fieldName))
            {
                Class< ? > objClass = object.getClass();
                if (objClass != fieldType)
                {
                    out.writeFieldName(JSON.DEFAULT_TYPE_KEY);
                    serializer.write(object.getClass());
                    commaFlag = true;
                }
            }

            char seperator = commaFlag ? ',' : '\0';

            char newSeperator = FilterUtils.writeBefore(serializer, object, seperator);
            commaFlag = newSeperator == ',';
            
            if (ordinalEnable)
            {
                writeSplit(serializer, out, commaFlag);
                Enum<?> e = (Enum<?>) object;
                if (!writeAsArray)
                {
                    out.writeFieldName("name");
                }
                serializer.write(e.name());
                commaFlag = true;
            }
            if (nameEnable)
            {
                writeSplit(serializer, out, commaFlag);
                Enum<?> e = (Enum<?>) object;
                if (!writeAsArray)
                {
                    out.writeFieldName("ordinal");
                }
                out.writeInt(e.ordinal());
                commaFlag = true;
            } 

            for (int i = 0; i < getters.length; ++i)
            {
                FieldSerializer fieldSerializer = getters[i];

                if (serializer.isEnabled(SerializerFeature.SkipTransientField))
                {
                    Field field = fieldSerializer.getField();
                    if (field != null)
                    {
                        if (Modifier.isTransient(field.getModifiers()))
                        {
                            continue;
                        }
                    }
                }

                if (!FilterUtils.applyName(serializer, object, fieldSerializer.getName()))
                {
                    continue;
                }

                Object propertyValue = fieldSerializer.getPropertyValue(object);

                if (!FilterUtils.apply(serializer, object, fieldSerializer.getName(), propertyValue))
                {
                    continue;
                }

                String key = FilterUtils.processKey(serializer, object, fieldSerializer.getName(), propertyValue);

                Object originalValue = propertyValue;
                propertyValue = FilterUtils.processValue(serializer, object, fieldSerializer.getName(), propertyValue);

                if (propertyValue == null && !writeAsArray)
                {
                    if ((!fieldSerializer.isWriteNull()) && (!serializer.isEnabled(SerializerFeature.WriteMapNullValue)))
                    {
                        continue;
                    }
                }
                
                writeSplit(serializer, out, commaFlag);
                
                if (key != fieldSerializer.getName())
                {
                    if (!writeAsArray)
                    {
                        out.writeFieldName(key);
                    }
                    serializer.write(propertyValue);
                }
                else if (originalValue != propertyValue)
                {
                    if (!writeAsArray)
                    {
                        fieldSerializer.writePrefix(serializer);
                    }
                    serializer.write(propertyValue);
                }
                else
                {
                    if (!writeAsArray)
                    {
                        fieldSerializer.writeProperty(serializer, propertyValue);
                    }
                    else
                    {
                        fieldSerializer.writeValue(serializer, propertyValue);
                    }
                }

                commaFlag = true;
            }

            FilterUtils.writeAfter(serializer, object, commaFlag ? ',' : '\0');

            if (getters.length > 0 && out.isEnabled(SerializerFeature.PrettyFormat))
            {
                serializer.decrementIdent();
                serializer.println();
            }

            out.append(endSeperator);
        }
        catch(Exception e)
        {
            throw new JSONException("write javaBean error", e);
        }
        finally
        {
            serializer.setContext(parent);
        }
    }

    
    private void writeSplit(JSONSerializer serializer, SerializeWriter out, boolean commaFlag)
    {
        if (commaFlag)
        {
            out.append(',');
            if (out.isEnabled(SerializerFeature.PrettyFormat))
            {
                serializer.println();
            }
        }
    }
    
    private boolean isWriteClassName(JSONSerializer serializer, Object obj, Type fieldType,
        Object fieldName)
    {
        return serializer.isWriteClassName(fieldType, obj);
    }

    private FieldSerializer createFieldSerializer(FieldInfo fieldInfo)
    {
        Class< ? > clazz = fieldInfo.getFieldClass();

        if (clazz == Number.class)
        {
            return new NumberFieldSerializer(fieldInfo);
        }

        return new ObjectFieldSerializer(fieldInfo);
    }

}
